package com.xiaoq.social.repository.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.social.entity.FavoriteEntity;
import com.xiaoq.social.repository.IFavoriteRepository;
import com.xiaoq.vo.PagingVo;
@Repository
public class FavoriteRepositoryImpl implements IFavoriteRepository {
	
	@Autowired
	private Datastore datastore;
	
	@Autowired
	private IdGenerator idGenerator;
	
	private static final Logger LOG = LoggerFactory.getLogger(FavoriteRepositoryImpl.class);

	@Override
	public boolean isFavorite(String userId, String tgtId) {
		Query<FavoriteEntity> favoriteQuery = datastore.createQuery(FavoriteEntity.class);
		if(StringUtils.isNotEmpty(tgtId)&&StringUtils.isNotEmpty(userId)){
			FavoriteEntity favorite = favoriteQuery.field("userId").equal(userId).field("targetId").equal(tgtId).get();
			if(favorite!=null){
				LOG.info(userId+"已经收藏"+tgtId);
				return true;
			}else{
				LOG.info(userId+"未收藏"+tgtId);
			}
			
		}else{
		LOG.error("tgtId或者userId不能为空会报空指针异常！");
		}
		return false;
	}

	@Override
	public boolean addFavorite(FavoriteEntity favorite) {
		if(favorite!=null){
			String id = idGenerator.nextId();
			LOG.info("FavoriteEntity添加的Id为： "+id);
			favorite.setId(id);
			datastore.save(favorite);
			return true;
		}else{
			LOG.error("收藏内容不能为空！");
		}
		return false;
	}

	@Override
	public boolean delFavorite(String userId, String tgtId) {
		Query<FavoriteEntity> favoriteQuery = datastore.find(FavoriteEntity.class);
		if(StringUtils.isNotEmpty(userId)&&StringUtils.isNotEmpty(tgtId)){
			favoriteQuery.field("userId").equal(userId).field("targetId").equal(tgtId);
			datastore.delete(favoriteQuery);
			return true;
		}else{
			LOG.error("取消收藏参数不能为空！");
		}
		return false;
	}

	@Override
	public List<FavoriteEntity> findFavoriteList(String userId,PagingVo pvo) {
		int ps = pvo.getPs();
		int pn = (pvo.getPn() - 1) * ps;
		Query<FavoriteEntity> favoriteQuery = datastore.find(FavoriteEntity.class);
		List<FavoriteEntity> favoriteList = new ArrayList<FavoriteEntity>();
		Long total = 0L;
		if(StringUtils.isNoneEmpty(userId)){
			favoriteQuery.field("userId").equal(userId);
			if(favoriteQuery.count()!=0){
				total = favoriteQuery.count();
				pvo.setTc(total);
				favoriteQuery.order("-createdAt").offset(pn).limit(ps);
				favoriteList = favoriteQuery.asList();
				
			}else{
				LOG.debug("该用户还没有任何收藏！");
			}
			}
		return favoriteList;
	}

	@Override
	public boolean delFavoriteByTgtId(String tgtId) {
		Query<FavoriteEntity> favoriteQuery = datastore.find(FavoriteEntity.class).field("targetId").equal(tgtId);
		datastore.delete(favoriteQuery);
		return true;
	}
	

}
